package com.zhfi.dataapply.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Slf4j
@Configuration
public class BatchConfig {

    @Bean
    public JobRepositoryFactoryBean jobRepositoryFactoryBean(DataSource dataSource, PlatformTransactionManager transactionManager){
        JobRepositoryFactoryBean jobRepositoryFactoryBean = new JobRepositoryFactoryBean();
        jobRepositoryFactoryBean.setTransactionManager(transactionManager);
        jobRepositoryFactoryBean.setDataSource(dataSource);
        jobRepositoryFactoryBean.setIsolationLevelForCreate("ISOLATION_READ_COMMITTED");
        try {
            jobRepositoryFactoryBean.afterPropertiesSet();
        } catch (Exception e) {
            log.error("创建jobRepositoryFactoryBean异常：{}",e.getMessage());
        }
        return  jobRepositoryFactoryBean;
    }

    @Bean
    public JobRepository ajobRepository(JobRepositoryFactoryBean jobRepositoryFactoryBean){
        JobRepository jobRepository = null;
        try {
            jobRepository = jobRepositoryFactoryBean.getObject();
        } catch (Exception e) {
            log.error("创建jobRepository异常{}",e.getMessage());
        }
        return jobRepository;
    }

    @Bean
    public SimpleJobLauncher simpleJobLauncher(@Qualifier("ajobRepository") JobRepository jobRepository){
        SimpleJobLauncher  simpleJobLauncher = new SimpleJobLauncher();
        simpleJobLauncher.setJobRepository(jobRepository);
        try {
            simpleJobLauncher.afterPropertiesSet();
        } catch (Exception e) {
            log.error("创建simpleJobLauncher异常：{}",e.getMessage());
        }
        return simpleJobLauncher;
    }

}
